package com.xw.musicplayer.floatView;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.xw.musicplayer.MusicPlayer;
import com.xw.musicplayer.PlayController;
import com.xw.musicplayer.R;
import com.xw.musicplayer.bean.Music;
import com.xw.musicplayer.listener.OnMusicChangeListener;
import com.xw.musicplayer.listener.OnProgressListener;
import com.xw.musicplayer.listener.OnStatusChangeListener;
import com.xw.musicplayer.utils.PlayStatus;

/**
 * 悬浮窗布局
 */
public class FloatLayout extends FrameLayout implements View.OnClickListener, OnStatusChangeListener, OnMusicChangeListener, OnProgressListener {

    private Context mContext;
    private WindowManager windowManager;
    private ImageView mFloatView;
    private ImageView imageLast;
    private ImageView imageStart;
    private ImageView imageNext;
    private ImageView imageCancle;
    private View view;
    private LinearLayout linearMenu;
    private FloatRoundSeekBar floatSeekbar;
    private RequestOptions options;
    //屏幕宽度
    private int screenWidth;
    private int x;
    private int y;

    //当前悬浮窗操作布局是否显示
    private boolean isShowImageBtn = false;
    //悬浮窗是否被销毁
    private boolean isWindowLive;

    //手指按下的坐标
    private float mTouchStartX;
    private float mTouchStartY;

    private WindowManager.LayoutParams mWmParams;
    private Handler handler = new Handler();

    public FloatLayout(@NonNull Context context) {
        this(context,null);
    }

    public FloatLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public FloatLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        mContext = context;
        windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        LayoutInflater.from(context).inflate(R.layout.float_normal_view, this);

        //浮动窗口按钮
        mFloatView = findViewById(R.id.iv_show_control_view);
        imageLast = findViewById(R.id.image_last);
        imageStart = findViewById(R.id.image_start);
        imageNext = findViewById(R.id.image_next);
        imageCancle = findViewById(R.id.image_cancle);
        view = findViewById(R.id.ll_float_normal);
        linearMenu = findViewById(R.id.linear_menu);
        floatSeekbar = findViewById(R.id.float_seekbar);

        view.setVisibility(GONE);
        DisplayMetrics dm = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(dm);
        screenWidth = dm.widthPixels;

        mFloatView.setOnClickListener(this);
        imageLast.setOnClickListener(this);
        imageStart.setOnClickListener(this);
        imageNext.setOnClickListener(this);
        imageCancle.setOnClickListener(this);

        options = new RequestOptions().placeholder(R.mipmap.float_music_icon)
                .error(R.mipmap.float_music_icon).circleCrop();
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        // 获取相对屏幕的坐标，即以屏幕左上角为原点
        x = (int) event.getRawX();
        y = (int) event.getRawY();

        //下面的这些事件，跟图标的移动无关，为了区分开拖动和点击事件
        int action = event.getAction();
        switch (action) {

            case MotionEvent.ACTION_DOWN:

                mTouchStartX = event.getX();
                mTouchStartY = event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                //图标移动
                float mMoveStartX = event.getX();
                float mMoveStartY = event.getY();

                //如果运动量大于3 则移动
                if (Math.abs(mTouchStartX - mMoveStartX) > 3 && Math.abs(mTouchStartY - mMoveStartY) > 3) {
                    mWmParams.x = (int) (x - mTouchStartX);
                    mWmParams.y = (int) (y - mTouchStartY);

                    windowManager.updateViewLayout(this,mWmParams);
                    return super.onInterceptTouchEvent(event);
                }
                break;
            case MotionEvent.ACTION_UP:
                float endX = event.getRawX();
                //根据最终手指停留位置，悬浮窗吸边效果实现
                if (endX > screenWidth / 2) {
                    mWmParams.x = screenWidth - getWidth();
                } else {
                    mWmParams.x = 0;
                }

                windowManager.updateViewLayout(this,mWmParams);
                float upX = event.getX();
                float upY = event.getY();
                //view移动轨迹大于30  ，不处理子View点击事件
                if(Math.abs(upX-mTouchStartX) > 30 && Math.abs(upY - mTouchStartY) > 30){
                    return true;
                }
                break;

            default:
                break;
        }

        return super.onInterceptTouchEvent(event);
    }

    @Override
    public void onClick(View v) {

        if (isShowImageBtn) {
            handler.removeCallbacks(runnable);
        }
        int id = v.getId();
        if (id == R.id.iv_show_control_view) {
            if (!isShowImageBtn) {
                linearMenu.setVisibility(VISIBLE);
                isShowImageBtn = true;
            } else {
                linearMenu.setVisibility(GONE);
                isShowImageBtn = false;
                adscrop();
            }
        } else if (id == R.id.image_last) {
            if (MusicPlayer.isInitialize()) {
                MusicPlayer.getInstance().playPrevious();
            }
        } else if (id == R.id.image_next) {
            if (MusicPlayer.isInitialize()) {
                MusicPlayer.getInstance().playNext();
            }
        } else if (id == R.id.image_start) {
            if (MusicPlayer.isInitialize()) {
                if (MusicPlayer.getInstance().isPlaying()) {
                    MusicPlayer.getInstance().pause();
                } else {
                    MusicPlayer.getInstance().play();
                }
            }
        } else if (id == R.id.image_cancle) {
            if (MusicPlayer.isInitialize()) {
                MusicPlayer.getInstance().closePlayService();
                MusicPlayer.getInstance().hideFloatWindow();
                MusicPlayer.getInstance().removeFloatWindow();
            }
        }

        handler.postDelayed(runnable,3000);
    }

    /**
     * 定时任务，吸边悬浮窗
     */
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            isShowImageBtn = false;
            linearMenu.setVisibility(GONE);
            adscrop();
        }
    };

    /**
     * 吸边
     */
    private void adscrop() {
//        if (isWindowLive) {

            if (x > screenWidth / 2) {
                mWmParams.x = screenWidth;
            } else {
                mWmParams.x = 0;
            }

            windowManager.updateViewLayout(this,mWmParams);
//        }
    }

    /**
     * 将小悬浮窗的参数传入，用于更新小悬浮窗的位置。
     */
    public void setParams(WindowManager.LayoutParams params) {
        mWmParams = params;
    }

    /**
     * 更新UI
     */
    public void upDateUI() {

    }

    /**
     * 设置最大进度条
     */
    public void setMaxProgress(int maxProgress) {
        floatSeekbar.setMax(maxProgress);
    }

    /**
     * 更新进度条
     */
    public void updateProgress(int progress) {
        floatSeekbar.setProgress(progress);
    }

   public void hide() {
        view.setVisibility(GONE);
   }

   public void show() {
        view.setVisibility(VISIBLE);
        if (linearMenu.getVisibility() == View.VISIBLE) {
            linearMenu.setVisibility(GONE);
        }

        adscrop();
   }

    /**
     * 移除悬浮窗，清除数据
     */
   public void remove() {
        MusicPlayer.getInstance().unregisterStatusChangeListener(this);
        MusicPlayer.getInstance().unregisterMusicChangeListener(this);
   }

    @Override
    public void onStatusChange(int status) {
        Log.d("info","====当前状态==" + status);
        if (!MusicPlayer.isInitialize()) {
            imageStart.setImageResource(R.mipmap.float_image_start);
            return;
        }

        if (status == PlayStatus.STATE_RELEASE) {
            remove();
            MusicPlayer.getInstance().removeFloatWindow();
        }

        if (status == PlayStatus.STATE_PAUSE || status == PlayStatus.STATE_IDLE) {
            imageStart.setImageResource(R.mipmap.float_image_start);
        } else if (status == PlayStatus.STATE_PLAYING || status == PlayStatus.STATE_PREPARING) {
            imageStart.setImageResource(R.mipmap.float_image_stop);
        }
    }

    public void setChangeListener() {
        if (MusicPlayer.isInitialize()) {
            MusicPlayer.getInstance().registerStatusChangeListener(this);
            MusicPlayer.getInstance().registerMusicChangeListener(this);
            MusicPlayer.getInstance().registerProgressListener(this);
        }
    }

    @Override
    public void onMusicChange(int newPosition, int oldPosition) {
        setMusicDdata(newPosition);
    }

    public void setMusicDdata(int newPosition) {
        Music music = MusicPlayer.getInstance().getMusic(newPosition);
        setMusicDdata(music);
    }

    public void setMusicDdata(Music music) {
        String imgPath = music.iamgePath;
        Glide.with(mContext)
                .load(imgPath)
                .apply(options)
                .into(mFloatView);
    }


    @Override
    public void onProgress(long current, long duration, int bufferedPercentage) {

       floatSeekbar.setMax((int) duration);
       floatSeekbar.setProgress((int) current);
    }
}
